package com.jby.seckill.controller;

import com.jby.seckill.pojo.User;
import com.jby.seckill.service.IGoodsService;
import com.jby.seckill.service.IUserService;
import com.jby.seckill.vo.DetailVo;
import com.jby.seckill.vo.GoodsVo;
import com.jby.seckill.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Description 商品
 * @Author Jiang
 * @Date 2021/12/16 19:21
 * @Version 1.0.0
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    IUserService userService;

    @Autowired
    IGoodsService goodsService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 商品列表页
     * 优化前压测：上午9：30
     * Windows压测优化前QPS: 301.1
     * 缓存后QPS: 364.3
     *
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {

        //如果缓存不为空，返回缓存
        ValueOperations valueOperations = redisTemplate.opsForValue();

        String html = (String) valueOperations.get("goodsList");

        if (!StringUtils.isEmpty(html)) {
            return html;
        }

        model.addAttribute("user", user);

        model.addAttribute("goodsList", goodsService.findGoodsVo());

        //构建html模板
        WebContext context = new WebContext(request, response, request.getServletContext(),
                request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);
        //构建缓存
        if (!StringUtils.isEmpty(html)) {
            valueOperations.set("goosdList", html, 60, TimeUnit.SECONDS);
        }
        return html;
    }

//    @RequestMapping(value = "/toList")
//    public String toList(Model model, User user) {
//
//
//
//        model.addAttribute("user", user);
//
//        model.addAttribute("goodsList", goodsService.findGoodsVo());
//
//        return "goodsList";
//    }

    @RequestMapping(value = "/detail/{goodsId}")
    @ResponseBody
    public RespBean toDetail(Model model, User user, @PathVariable Long goodsId,
                             HttpServletRequest request, HttpServletResponse response) {


        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态,0未开始，1进行中，2已结束
        int seckillStatus = 0;
        //秒杀开始倒计时
        int remainSecondsOfStart = 0;

        //秒杀结束倒计时
        int remainSecondsOfEnd = 0;

        //秒杀未开始
        if (startDate.after(nowDate)) {
            //秒杀开始倒计时
            remainSecondsOfStart = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
            remainSecondsOfEnd = 0;
            //秒杀结束倒计时
            remainSecondsOfEnd = (int) (((endDate.getTime() - nowDate.getTime()) / 1000) - ((startDate.getTime() - nowDate.getTime()) / 1000));
            //秒杀已结束
        } else if (endDate.before(nowDate)) {
            seckillStatus = 2;
            remainSecondsOfStart = -1;
            remainSecondsOfEnd = -1;
            //秒杀进行中
        } else {
            seckillStatus = 1;
            remainSecondsOfStart = 0;
            remainSecondsOfEnd = (int) ((endDate.getTime() - nowDate.getTime()) / 1000);
        }

        DetailVo detailVo = new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVo(goodsVo);
        detailVo.setSeckillStatus(seckillStatus);
        detailVo.setRemainSecondsOfStart(remainSecondsOfStart);
        detailVo.setRemainSecondsOfEnd(remainSecondsOfEnd);

        return RespBean.success(detailVo);
    }
}
